// pages/PlaceOrder/index.js
import { formatDate, formatTime} from '../../utils/util.js'
import api from '../../request/api.js'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify.js';
var app = getApp()
var date = new Date();
var currentHours = date.getHours();
var currentMinute = date.getMinutes();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    model:{
      username:'',
      phone:'',
      village:'',
      date:'',
      quantity:''
    },
    dateShow: false,
    timeShow: false,
    minDate: new Date().getTime(),
    maxDate: new Date(2019, 10, 1).getTime(),
    currentDate: new Date().getTime(),
    currentTime: '00:01',
    error: '',
    newcurrent:'',
    index_va: 0,
    category_name:'',
    areaList: [],
    community_id: '',
    addressId: '', //地址id
    imageUrl: 'http://feishoukeji.com:8080/Recycle/static/image/',
    category_id:'', //类别id
    startDate: "立即上门",

    multiArray: [['今天', '明天', '3-2', '3-3', '3-4', '3-5'], [0, 1, 2, 3, 4, 5, 6], [0, 10, 20]],
    multiIndex: [0, 0, 0],
  },
  //获取默认地址
  async getDefaultArea(){
    const village = 'model.village'
    const { data: res } = await api('GET','Recycle/address/getDefaultAddr',{
      token: wx.getStorageSync('token')
    })
    if(res.code===200){
      let a = res.data.addr_prefix + res.data.community_name + res.data.addr_detail
      this.setData({
        [village]: a,
        addressId: res.data.address_id
      })
    }
  },
  //选择小区
  choosevillage(e){
    wx.navigateTo({
      url: '../address/index?type=order',
    })
  },
  //选择日期
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  //选择时间
  onInputTime(event){
    this.setData({
      currentTime: event.detail
    })
  },
  chooseDate(){
    this.setData({
      dateShow:true
    })
  },
  dateConfirm(e){
    let a = formatDate(e.detail)
    this.setData({
      dateShow:false,
      timeShow:true,
      newcurrent: a
    })
  },
  dateCancel(){
    this.setData({
      dateShow: false,
      timeShow: false
    })
  },
  //选择开始和结束时间
  chooseTime(e){
    let a = e.detail.split(':')
    let startEnd = ' ' + a[0] + ':00' + '-' + a[1] + ':' +'00';
    let { newcurrent} = this.data
    let date = 'model.date'
    if(a[0]>a[1]){
      Notify('结束时间必须大于开始时间');
    }else{
      this.setData({
        startEnd:a,
        timeShow:false,
        [date]: newcurrent + startEnd
      })
    }
  },

  //提交订单
  async formSubmit(e){
    if(!app.globalData.agree){Toast('请确认肥收环保上门回收免责');return;}
    // let date2 = 'model.date'
    let village2 = 'model.village'
    let quantity2 = 'model.quantity'
    const { addressId, category_id} = this.data
    const { quantity} = e.detail.value

    let date = Date.parse(new Date(this.data.startDate));
    if(this.data.startDate == '立即上门'){
      date = new Date().getTime();
    }
    if(!addressId){Toast('请输入地址');return;}
    if(!date){Toast('请选择时间');return;}
    if(!quantity){Toast('请输入数量');return;}
    if(!category_id){Toast('请选择分类');return;}
      const { data: res } = await api('POST', 'Recycle/order/addOrder', {
        token: wx.getStorageSync('token'),
        addressId,
        serviceTime: date,
        category_id,
        quantity
      })
      if(res.code == 200){
        Toast('下单成功')
        this.setData({
          // [date2]:'',
          [village2]:'',
          [quantity2]: ''
        })
        wx.removeStorageSync('orderAddress')
        wx.navigateTo({
          url: '../orderDetail/index?id='+res.data,
      })
      }
  },
  async getAllareaList() {
    const res = await api('GET', 'Recycle/area/getCommunities',({pageNum:1,pageSize:100}))
    if (res.data.code === 200) {
      this.setData({
        areaList: res.data.data
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let category = wx.getStorageSync('category')
    this.setData({
      category_name: category.category_name,
      category_id: category.category_id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const village = 'model.village'
    this.getAllareaList()
    let addressOrder = wx.getStorageSync('orderAddress')
    let a = addressOrder.addr_prefix + addressOrder.community_name + addressOrder.addr_detail
    if(!addressOrder.address_id){
      this.getDefaultArea();
    }
    if (addressOrder){
      this.setData({
        [village]: a,
        addressId: addressOrder.address_id
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  pickerTap:function() {
    date = new Date();

    var monthDay = ['今天','明天'];
    var hours = [];
    var minute = [];
    
    currentHours = date.getHours();
    currentMinute = date.getMinutes();

    // 月-日
    for (var i = 2; i <= 28; i++) {
      var date1 = new Date(date);
      date1.setDate(date.getDate() + i);
      var md = (date1.getMonth() + 1) + "-" + date1.getDate();
      monthDay.push(md);
    }
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    if(data.multiIndex[0] === 0) {
      if(data.multiIndex[1] === 0) {
        this.loadData(hours, minute);
      } else {
        this.loadMinute(hours, minute);
      }
    } else {
      this.loadHoursMinute(hours, minute);
    }

    data.multiArray[0] = monthDay;
    data.multiArray[1] = hours;
    data.multiArray[2] = minute;

    this.setData(data);
  },
  bindMultiPickerColumnChange:function(e) {
    date = new Date();

    var that = this;

    var monthDay = ['今天', '明天'];
    var hours = [];
    var minute = [];

    currentHours = date.getHours();
    currentMinute = date.getMinutes();

    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    // 把选择的对应值赋值给 multiIndex
    data.multiIndex[e.detail.column] = e.detail.value;
    // 然后再判断当前改变的是哪一列,如果是第1列改变
    if (e.detail.column === 0) {
      // 如果第一列滚动到第一行
      if (e.detail.value === 0) {

        that.loadData(hours, minute);
        
      } else {
        that.loadHoursMinute(hours, minute);
      }

      data.multiIndex[1] = 0;
      data.multiIndex[2] = 0;

      // 如果是第2列改变
    } else if (e.detail.column === 1) {

      // 如果第一列为今天
      if (data.multiIndex[0] === 0) {
        if (e.detail.value === 0) {
          that.loadData(hours, minute);
        } else {
          that.loadMinute(hours, minute);
        }
        // 第一列不为今天
      } else {
        that.loadHoursMinute(hours, minute);
      }
      data.multiIndex[2] = 0;

      // 如果是第3列改变
    } else {
      // 如果第一列为'今天'
      if (data.multiIndex[0] === 0) {

        // 如果第一列为 '今天'并且第二列为当前时间
        if(data.multiIndex[1] === 0) {
          that.loadData(hours, minute);
        } else {
          that.loadMinute(hours, minute);
        }
      } else {
        that.loadHoursMinute(hours, minute);
      }
    }
    data.multiArray[1] = hours;
    data.multiArray[2] = minute;
    this.setData(data);
  },

  loadData: function (hours, minute) {

    var minuteIndex;
    if (currentMinute > 0 && currentMinute <= 10) {
      minuteIndex = 10;
    } else if (currentMinute > 10 && currentMinute <= 20) {
      minuteIndex = 20;
    } else if (currentMinute > 20 && currentMinute <= 30) {
      minuteIndex = 30;
    } else if (currentMinute > 30 && currentMinute <= 40) {
      minuteIndex = 40;
    } else if (currentMinute > 40 && currentMinute <= 50) {
      minuteIndex = 50;
    } else {
      minuteIndex = 60;
    }

    if (minuteIndex == 60) {
      // 时
      for (var i = currentHours + 1; i < 24; i++) {
        hours.push(i);
      }
      // 分
      for (var i = 0; i < 60; i += 10) {
        minute.push(i);
      }
    } else {
      // 时
      for (var i = currentHours; i < 24; i++) {
        hours.push(i);
      }
      // 分
      for (var i = minuteIndex; i < 60; i += 10) {
        minute.push(i);
      }
    }
  },

  loadHoursMinute: function (hours, minute){
    // 时
    for (var i = 0; i < 24; i++) {
      hours.push(i);
    }
    // 分
    for (var i = 0; i < 60; i += 10) {
      minute.push(i);
    }
  },

  loadMinute: function (hours, minute) {
    var minuteIndex;
    if (currentMinute > 0 && currentMinute <= 10) {
      minuteIndex = 10;
    } else if (currentMinute > 10 && currentMinute <= 20) {
      minuteIndex = 20;
    } else if (currentMinute > 20 && currentMinute <= 30) {
      minuteIndex = 30;
    } else if (currentMinute > 30 && currentMinute <= 40) {
      minuteIndex = 40;
    } else if (currentMinute > 40 && currentMinute <= 50) {
      minuteIndex = 50;
    } else {
      minuteIndex = 60;
    }

    if (minuteIndex == 60) {
      // 时
      for (var i = currentHours + 1; i < 24; i++) {
        hours.push(i);
      }
    } else {
      // 时
      for (var i = currentHours; i < 24; i++) {
        hours.push(i);
      }
    }
    // 分
    for (var i = 0; i < 60; i += 10) {
      minute.push(i);
    }
  },

  bindStartMultiPickerChange: function (e) {
    var that = this;
    var monthDay = that.data.multiArray[0][e.detail.value[0]];
    var hours = that.data.multiArray[1][e.detail.value[1]];
    var minute = that.data.multiArray[2][e.detail.value[2]];

    if (monthDay === "今天") {
      var month = date.getMonth()+1;
      var day = date.getDate();
      monthDay = month + "月" + day + "日";
    } else if (monthDay === "明天") {
      var date1 = new Date(date);
      date1.setDate(date.getDate() + 1);
      month = date1.getMonth() + 1;
      day = date1.getDate();
      monthDay = month + "月" + day + "日";
    } else {
      var month = monthDay.split("-")[0]; // 返回月
      var day = monthDay.split("-")[1]; // 返回日
      monthDay = month + "月" + day + "日";
    }
    var year = date.getFullYear();
    if(month < 10) month = "0" + month;
    if(day < 10) day = "0" + day;
    if(hours < 10) hours = "0" + hours;
    if(minute < 10) minute = "0" + minute;
    var startDate =  year + "/" + month + "/" + day + " " + hours + ":" + minute + ":" + "00";
    that.setData({
      startDate: startDate
    })
  }
})